<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>附件管理中心</title>
<link href="/Public/Common/attach/css/reset.css" rel="stylesheet" type="text/css" />
<link href="/Public/Common/attach/css/zh-cn-system.css" rel="stylesheet" type="text/css" />
<link href="/Public/Common/attach/css/table_form.css" rel="stylesheet" type="text/css" />
<link href="__PLUGIN__/plupload/swfupload.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="__PLUGIN__/jquery/jquery-1.9.min.js"></script>
<style type="text/css">html{_overflow-y:scroll}</style>
<script language="JavaScript" type="text/javascript" src="__PLUGIN__/plupload/handlers.js"></script>
<script src="__PLUGIN__/plupload/js/plupload.full.min.js"></script>

<script>

	let m="{$module}";	
	//配置
	var file_num={$num};//文件上传数量
	var dx=<?php echo ($num>1) ? 'true' : 'false'; ?>; //是否多选
	$(function(){
			var pconfig={
				browse_button : "addnew", //点击触发文件选择框
				url :"{:U('Attach/edit',array('module'=>$module,'save_path'=>$save_path,'cid'=>$cid))}",
				flash_swf_url : '__PLUGIN__/plupload/js/Moxie.swf', //swf文件
        		silverlight_xap_url : '__PLUGIN__/plupload/js/Moxie.xap', //silverlight文件
        		multi_selection: dx,
        		filters: {
					mime_types : [ //只允许上传图片和zip文件
					{ title : "file_types", extensions : "{$pl_exts}" }, 
					],
					max_file_size : "{$sizes}mb", //最大只能上传文件尺寸
					prevent_duplicates : false //允许选取重复文件,true不允许
				},
				file_data_name : 'Filedata', //文件上传名
				runtimes :"flash,html5,silverlight,html4"
			};

			var uploader = new plupload.Uploader(pconfig);
			uploader.init();

			//点击开始上传、
			$("#btupload").click(function(){
				uploader.start(); 
			});


			function removeFile(fid){
				uploader.removeFile(fid);
			}

			//filelist是uploader上传队列 ; display是列表展示js数组 ; 通过与上传队列对比，来确定展示的内容
			function ck_files(filelist,display){
				if(display.length===0){
					console.log('这是空展示列表');
					return [];
				}
				let kary=[];
				//有展示内容
				for(x in filelist){
					let ckfid=filelist[x].id;
					if($("#fsUploadProgress #"+ckfid).length===1 && $("#fsUploadProgress #"+ckfid) !== 'undefined'){
						kary.push(ckfid);
					}
				}
				return kary;
			}

				//未上传时的删除方法
			$(document).on('click','a.progressCancel',function(){
				let fid=$(this).attr('fid');
				let file_obj=uploader.getFile(fid);
				$("#fsUploadProgress").find("#"+fid).remove();
				uploader.removeFile(file_obj);
			})

			//文件添加到上队列后触发的 监听函数
    		uploader.bind('FilesAdded', function(up, files) {
		        //up为当前的plupload实例对象 ；files是 《本次》 添加到上传队列的文件
		          if(up.files.length>file_num){ // 最多上传3张图 ，可用php数量变量
			            dary=up.splice(file_num,999);
			            alert('最多'+file_num+'个');
			        }
			        // console.log(up.files);
			        //判断展示列表的是否有数量是否与当前队列数量，和本次上传数量对比
			        //情况1 一次上传满，比如一次上传2个。
			        //情况2 多次上传满，一次一个。
			        //总结 判断当前文件队列 和 展示内容中的是否存在存在就不添加展示列表 对
			        
			        //1获取展示列表
			        let display=$("#fsUploadProgress").children();
			        // console.log(display);
			        let test=ck_files(up.files,display);

			        // console.log(up.files);
			        // console.log(test);

		        var html = '';
		        //pluoload.each(文件对象，索引)
		        plupload.each(up.files, function(file,index) {

		        	if(test.indexOf(file.id)==-1){
		        		html+='<div class="progressWrapper" id="'+file.id+'">'+
		        '<div class="progressContainer">'+
		        '<a class="progressCancel" href="javascript:;" fid="'+file.id+'" style="visibility: visible;"></a>'+
		        '<div class="progressName">'+file.name+'</div>'+
		        '<div class="progressBarStatus">&nbsp;</div>'+
		        '<div class="progressBarInProgress"></div>'+
		        '</div></div>';
		        	}
		         	
		        });
		        $("#fsUploadProgress").prepend(html);
		        // console.log(up.files);
		        console.log('FilesAdded end');
		      });

    		//进度条展示
    		uploader.bind('UploadProgress',function(uploader,file){
    			//文字div
		        var progress=$("#"+file.id).find(".progressBarInProgress");
		        progress.css('width',file.percent+'%');
		        //进度条宽度div
		        var progressBarStatus=$("#"+file.id).find(".progressBarStatus");
		        progressBarStatus.text(file.percent+'%');
		    });
    		//错误提示
			uploader.bind('Error', function(up, err) {
				console.log("Error #" + err.code + ": " + err.message);
		        // document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
		        var tstr='';
		        var timer=null;
		        var $undefined=null;
		        // var html='<div class="progressWrapper" id="undefined" style="opacity: 0; height: 0px; display: none;"><div class="progressContainer red"><a class="progressCancel" href="#" style="visibility: hidden;"> </a><div class="progressName">undefined</div><div class="progressBarStatus">文件尺寸超过设定值</div><div class="progressBarError"></div></div></div>';

		        if(err.code=='-601'){
		        	tstr="文件格式错误";
		        }
		        else if(err.code=='-600'){
		        	tstr="文件尺寸太大";
		        }else{
		        	tstr="其他错误";
		        }

		        var html='<div class="progressWrapper" id="undefined" style="opacity: 1;"><div class="progressContainer red"><a class="progressCancel" href="#" style="visibility: hidden;"> </a><div class="progressName">undefined</div><div class="progressBarStatus">'+tstr+'</div><div class="progressBarError"></div></div></div>';

		        //向首部插入
		        // console.log($("#fsUploadProgress").find("#undefined"));
		        $undefined=$("#fsUploadProgress").find("#undefined") ? $("#fsUploadProgress").find("#undefined") : null;
		        // console.log($undefined.length);
		        if($undefined.length==0){
		        	$("#fsUploadProgress").prepend(html);
		        }else{
		        	//将自己替换
		        	$undefined.replaceWith(html);
		        }

		        //倒计时隐藏
		        timer=setTimeout(function(){
		        	 clearTimeout(timer);
		        	// $("#fsUploadProgress").find("#undefined");
		        	// $("#fsUploadProgress").find("#undefined").css({"opacity":0,"height":"0px","display":"none"});
		        	$("#fsUploadProgress").find("#undefined").remove();
		        },3000);
		      });

			//上传成功回调
			uploader.bind('FileUploaded',function(uploader,files,data){
				/**
				uploader：当前实例的对象，
				files：被上传的文件
				data：返回值
				*/
				//获取隐藏路径标签元素
				var attStatus=$("#att-status"); //图片路径
				var attStatusDel=$("#att-status-del");
				var attName=$("#att-name"); //图片名称
				var imgInfo=data.response;
				
				var imgArr=imgInfo.split(',');
				var num=imgArr[0];
				var imgSrc=imgArr[1]; //文件展示路径
				var filePath=imgArr[1]; //文件路径
				var imgName=imgArr[3];
				var imgState=imgArr[2];

				//根据上传类型判断展示图片
				switch({$module}){
					case 0:
						imgSrc=imgSrc;
					break;
					case 1:
						imgSrc='/Public/Admin/img/ext/rar.png';
					break;
					case 2:
						imgSrc='/Public/Admin/img/ext/flv.png';
					break;
					default:
				}

				//创建缩略图展示html
				var html='<li><div id="attachment_'+num+'" class="img-wrap"><a href="javascript:;" onclick="javascript:att_cancel(this,'+num+',\'upload\')" class="on"><div class="icon"></div><img src="'+imgSrc+'" width="80" imgid="'+num+'" path="'+filePath+'" title="'+imgName+'"></a></div></li>';

				//改变进度条文本框类，隐藏。
				// console.log(files);
				$("#"+files.id).addClass('progresshidden');
				$("#"+files.id).css('opacity','1');
				$("#fsUploadProgress").append(html);



				//添加回调函数查找的值。
				attStatus.append('|'+filePath);
				attName.append('|'+imgName);
				// console.log(uploader.files);
				// console.log(imgArr);return false;

				
			});

			uploader.bind('FilesRemoved',function(uploader,files){
					//去除文件
					let len=files.length;
					// console.log('文件移除时间');
					for(let i=0; i<len;i++){
						let fid=files[i].id;
						uploader.removeFile(fid);
					}
					// console.log(uploader.files);
			});




	})
	
</script>


<div class="pad-10">
    <div class="col-tab">
        <ul class="tabBut cu-li">
            <li id="tab_swf_1"  class="on" onclick="SwapTab('swf','on','',5,1);">上传附件</li>
            <li id="tab_swf_2" onclick="SwapTab('swf','on','',5,2);">网络文件</li>
            <li id="tab_swf_3" onclick="SwapTab('swf','on','',5,3);set_iframe('album_list','{:U('search',array('num'=>$num,'size'=>$sizes,'ext'=>$exty,'module'=>$module))}');">数据库</li>            
        </ul>
		
         <div id="div_swf_1" class="content pad-10 ">
        	<div>
				<div class="addnew" id="addnew">
					<span id="buttonPlaceHolder"></span>
				</div>
				<!-- <input type="button" id="btupload" value="开始上传" onClick="swfu.startUpload();" /> -->
				<input type="button" id="btupload" value="开始上传"  />
                <div id="nameTip" class="onShow">最多上传<font color="red"> {$num}</font> 个附件,单文件最大 <font color="red">{$sizes} MB</font></div>
                <div class="bk3"></div>
				
                <div class="lh24">支持 <font style="font-family: Arial, Helvetica, sans-serif">{$exts}</font> 格式。</div>
				</div> 	
    		<div class="bk10"></div>
        	<fieldset class="blue pad-10" id="swfupload">
        	<legend>列表</legend>
        	<ul class="attachment-list"  id="fsUploadProgress">    
        	</ul>
    		</fieldset>
    	</div>
		
        <div id="div_swf_2" class="contentList pad-10 hidden">
        <div class="bk10"></div>
        	请输入网络地址<div class="bk3"></div><input type="text" name="info[filename]" class="input-text" value=""  style="width:350px;"  onblur="addonlinefile(this)">
		<div class="bk10"></div>
        </div>    	
		
    	<div id="div_swf_3" class="contentList pad-10 hidden">
            <ul class="attachment-list">
        	 <iframe name="album-list" src="#" frameborder="false" scrolling="no" style="overflow-x:hidden;border:none" width="100%" height="345" allowtransparency="true" id="album_list"></iframe>   
        	</ul>
        </div>
               
               
    <div id="att-status" class="hidden"></div>
    <div id="att-status-del" class="hidden"></div>
    <div id="att-name" class="hidden"></div>
                         
</div>
</body>
<script type="text/javascript">
function imgWrap(obj){
	$(obj).hasClass('on') ? $(obj).removeClass("on") : $(obj).addClass("on");
}

function SwapTab(name,cls_show,cls_hide,cnt,cur) {
    for(i=1;i<=cnt;i++){
		if(i==cur){
			 $('#div_'+name+'_'+i).show();
			 $('#tab_'+name+'_'+i).addClass(cls_show);
			 $('#tab_'+name+'_'+i).removeClass(cls_hide);
		}else{
			 $('#div_'+name+'_'+i).hide();
			 $('#tab_'+name+'_'+i).removeClass(cls_show);
			 $('#tab_'+name+'_'+i).addClass(cls_hide);
		}
	}
}

function addonlinefile(obj) {
	var strs = $(obj).val() ? '|'+ $(obj).val() :'';
	$('#att-status').html(strs);
}

function change_params(){
	if($('#watermark_enable').attr('checked')) {
		swfu.addPostParam('watermark_enable', '1');
	} else {
		swfu.removePostParam('watermark_enable');
	}
}
function set_iframe(id,src){
	$("#"+id).attr("src",src); 
}

function album_cancel(obj,id,source){
	var src = $(obj).children("img").attr("path"); //获取当前对象的子元素图片路径
	var filename = $(obj).attr('title');
	if($(obj).hasClass('on')){ //如果选中
		$(obj).removeClass("on");
		var imgstr = $("#att-status").html();
		var length = $("a[class='on']").children("img").length;
		console.log(length);
		var strs = filenames = '';
		//$.get('{:U('Attachment/edit',array('module'=>0))}?aid='+id+'&src='+source+'&filename='+filename);
		for(var i=0;i<length;i++){
			strs += '|'+$("a[class='on']").children("img").eq(i).attr('path');
			filenames += '|'+$("a[class='on']").children("img").eq(i).attr('title');
		}
		$('#att-status').html(strs);
		$('#att-status').html(filenames);
	} else {
		var num = $('#att-status').html().split('|').length;
		var file_upload_limit = '{$num}';
		if(num > file_upload_limit) {alert('不能选择超过'+file_upload_limit+'个附件'); return false;}
		$(obj).addClass("on");
		//$.get('{:U('Attachment/edit',array('module'=>0))}?aid='+id+'&src='+source+'&filename='+filename);
		$('#att-status').append('|'+src);
		$('#att-name').append('|'+filename);
	}
}

</script>
</html>
